from flask import Blueprint, request, jsonify
from app.services.user_service import UserService
from app.utils.response_handler import success_response, error_response
from app.utils.validation import validate_user_data

user_bp = Blueprint('user_bp', __name__)


@user_bp.route('', methods=['POST'])
def create_user():
    """创建用户"""
    data = request.json

    # 验证用户数据
    errors = validate_user_data(data)
    if errors:
        return error_response(errors, 400)

    try:
        new_user = UserService.create_user(data)
        return success_response(new_user.to_dict(), 201)
    except Exception as e:
        return error_response(str(e), 500)


@user_bp.route('', methods=['GET'])
def get_users():
    """获取所有用户"""
    try:
        users = UserService.get_all_users()
        return success_response([user.to_dict() for user in users])
    except Exception as e:
        return error_response(str(e), 500)


@user_bp.route('/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """获取单个用户"""
    try:
        user = UserService.get_user_by_id(user_id)
        return success_response(user.to_dict())
    except Exception as e:
        return error_response(str(e), 404)


@user_bp.route('/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    """更新用户信息"""
    data = request.json
    try:
        updated_user = UserService.update_user(user_id, data)
        return success_response(updated_user.to_dict())
    except Exception as e:
        return error_response(str(e), 400)


@user_bp.route('/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    """删除用户"""
    try:
        UserService.delete_user(user_id)
        return success_response({"message": "User deleted successfully"})
    except Exception as e:
        return error_response(str(e), 400)